package com.justnow.offer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author justnow
 * Created on 2020-09-21
 * Description
 */
public class Leetcode47_PermuteUnique {

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        int length = nums.length;
        Arrays.sort(nums);
        boolean[] used = new boolean[length];
        List<Integer> path = new ArrayList<>();
        dfs(0, path, nums, used);
        return res;
    }

    private void dfs(int depth, List<Integer> path, int[] nums, boolean[] used) {
        if (depth == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }

            if (i > 0 && nums[i] == nums[i-1] && !used[i - 1]) {
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            dfs(depth + 1, path, nums, used);
            used[i] = false;
            path.remove(path.size() - 1);
            
        }
    }
    

    public static void main(String[] args) {
        Leetcode47_PermuteUnique leetcode47_permuteUnique = new Leetcode47_PermuteUnique();
        List<List<Integer>> lists = leetcode47_permuteUnique.permuteUnique(new int[]{1, 1, 2});
        System.out.println(lists);
    }

}
